package lauglog.servlet;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import lauglog.bean.EventBean;
import lauglog.bean.PlanBean;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.sql.*;
import java.util.Calendar;
import java.util.Vector;
import lauglog.bean.UserBean;
import lauglog.bean.UserPlansBean;
import lauglog.util.MadePlan;

/**
 * 
 * 
 * 
 * @author Waseem
 */
@WebServlet(name = "Plans", urlPatterns = {"/Plans"})
public class PlansServlet extends HttpServlet {
    
    //This instance variable is used to uniquely identify 
    //events as they are being made during plan creation
    int eventCounter = 0;

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        //Here is where we do query string processing
        try {
            String action = request.getParameter("action");
            
            //called from planCreate.jsp when user enters tentative plan info
            //for a new plan during creation
            if (action.equalsIgnoreCase("make"))
                makePlan(request,response);
            
            //called form planDetail.jsp when an event is added during
            //plan creation
            else if (action.equalsIgnoreCase("event"))
                createEvent(request,response);
            
            //called when user searches for plans
            else if (action.equalsIgnoreCase("search"))
                searchPlan(request,response);
            
            //called when user finalizes a plan during creation
            //commits all the plan info to the db
            else if (action.equalsIgnoreCase("finish"))
                commitPlan(request,response);
            
            //called when user joins a plan
            else if (action.equalsIgnoreCase("join"))
                joinPlan(request,response);
            
            //called when doctor pushes a plan
            else if (action.equalsIgnoreCase("push"))
                pushPlan(request,response);
            else;
        } finally {            
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    
    private void pushPlan(HttpServletRequest request, HttpServletResponse response) throws IOException {
         //Declare items for the connection.
        String url = "jdbc:mysql://localhost/lauglog";
        String dbUserName = "root";
        String dbPassword = "";
        String driver = "com.mysql.jdbc.Driver";
        Connection con = null;
                
        try{
            //Instantiate the connection
            Class.forName(driver).newInstance();
            con = DriverManager.getConnection(url, dbUserName, dbPassword);
            
            int planId = Integer.parseInt(request.getParameter("planId"));
            int patientId = Integer.parseInt(request.getParameter("patientId"));
            int doctorId = Integer.parseInt(request.getParameter("doctorId"));
            
            PreparedStatement pushPlanStatement = con.prepareStatement("INSERT INTO doctorpushedplans (SenderId,ReceiverId,OriginalPlanId,CopiedPlanId) VALUES (?,?,?,?)");
            pushPlanStatement.setInt(1, doctorId);
            pushPlanStatement.setInt(2, patientId);
            pushPlanStatement.setInt(3, planId);
            pushPlanStatement.setInt(4, planId);
            pushPlanStatement.executeUpdate();
                        
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            try{
                con.close();
            }catch(Exception e1){
                e1.printStackTrace();
            }
        }
    }
    
    private void makePlan(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //Make a temporary bean to represent a tentative new plan
        PlanBean newPlan = new PlanBean();
        newPlan.setPlanName(request.getParameter("PlanName"));
        newPlan.setDuration(Integer.parseInt(request.getParameter("Duration")));
        newPlan.setDurationType(request.getParameter("DurationType"));
        newPlan.setSearchablePrivacy(request.getParameter("SearchablePrivacy"));
        newPlan.setViewablePrivacy(request.getParameter("ViewablePrivacy"));
        newPlan.setTags(request.getParameter("Tags"));
        HttpSession session = request.getSession();
        session.setAttribute("NewPlan",newPlan);
        response.sendRedirect("planDetail.jsp");
    }

    private void searchPlan(HttpServletRequest request, HttpServletResponse response) {
         //Declare items for the connection.
        String url = "jdbc:mysql://localhost/lauglog";
        String dbUserName = "root";
        String dbPassword = "";
        String driver = "com.mysql.jdbc.Driver";
        Connection con = null;
        
        String queryString = request.getParameter("q");
        
        PrintWriter out = null;
        
        try{
            out = response.getWriter();
        }catch(IOException ioe){
            
        }
        
        try{
            //Instantiate the connection
            Class.forName(driver).newInstance();
            con = DriverManager.getConnection(url, dbUserName, dbPassword);
            
            PreparedStatement searchPlanStatement = con.prepareStatement("SELECT PlanId, PlanName FROM Plans WHERE (PlanName LIKE '%"+queryString+"%' OR '"+queryString+"' LIKE '%PlanName%') AND SearchablePrivacy = 'Public'");
            ResultSet searchPlansRs = searchPlanStatement.executeQuery();
            
            UserPlansBean searchedPlansBean = new UserPlansBean();
            Vector<MadePlan> searchedPlansVector = new Vector();
            
            while(searchPlansRs.next()){
                MadePlan m = new MadePlan();
                m.setPlanID(searchPlansRs.getInt("PlanId"));
                m.setPlanName(searchPlansRs.getString("PlanName"));
                m.setJoined(false);
                searchedPlansVector.add(m);
            }
            
            searchedPlansBean.setListPlans(searchedPlansVector);
            request.getSession().setAttribute("searchedPlans", searchedPlansBean);
            
            response.sendRedirect("planSearchResults.jsp");
                        
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            try{
                con.close();
            }catch(Exception e1){
                e1.printStackTrace();
            }
        }
    }
    
    private void joinPlan(HttpServletRequest request, HttpServletResponse response) {
        
        //get reference to planId to join
        int planId = Integer.parseInt(request.getParameter("planId"));
        
        //find out what page you were navigated from
        String from = request.getParameter("from");
        
        //user data
        UserBean user = (UserBean)request.getSession().getAttribute("user");
        int userID = user.getUserID();
       
        
        int year = Integer.parseInt(request.getParameter("year"));
        int month = Integer.parseInt(request.getParameter("month"))-1;
        int day = Integer.parseInt(request.getParameter("day"));
        Calendar startDateCal = Calendar.getInstance();
        startDateCal.set(year,month,day,0,0,0);
        Date startDate = new Date(startDateCal.getTime().getTime());
        
        //Declare items for the connection.
        String url = "jdbc:mysql://localhost/lauglog";
        String dbUserName = "root";
        String dbPassword = "";
        String driver = "com.mysql.jdbc.Driver";
        Connection con = null;

        try{
            //Instantiate the connection
            Class.forName(driver).newInstance();
            con = DriverManager.getConnection(url, dbUserName, dbPassword);
            
            PreparedStatement getPlanInfoStatement = con.prepareStatement("SELECT Duration FROM plans WHERE PlanId = ?");
            getPlanInfoStatement.setInt(1, planId);
            ResultSet getPlanInfoRs = getPlanInfoStatement.executeQuery();
            getPlanInfoRs.first();
            int duration = getPlanInfoRs.getInt("Duration");
            
            PreparedStatement joinPlanStatement = con.prepareStatement("INSERT INTO joined_plans (PlanId,Duration,UserId,StartDate) VALUES (?,?,?,?)");
            joinPlanStatement.setInt(1, planId);
            joinPlanStatement.setInt(2, duration);
            joinPlanStatement.setInt(3, userID);
            joinPlanStatement.setDate(4, startDate);
            joinPlanStatement.executeUpdate();
            
            if (from.equals("search")){
                request.getSession().setAttribute("redirect", "plans.jsp");
                try{
                    response.sendRedirect("LoginServlet?action=updateBeans");
                }catch(Exception e){
                    
                }
            }else if (from.equals("list")){
                request.getSession().setAttribute("redirect", "listPlans.jsp");
                try{
                    response.sendRedirect("LoginServlet?action=updateBeans");
                }catch(Exception e){
                    
                }
            }else;
            
            
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            try{
                con.close();
            }catch(Exception e1){
                e1.printStackTrace();
            }
        }
        
        //update the userPlansBean
        //Get access to old bean
        updateUserPlansBean(request);
        
    }

    private void commitPlan(HttpServletRequest request, HttpServletResponse response) throws IOException {
        
        //Get access to temporary beans during plan creation
        HttpSession session = request.getSession();
        
        //Get the bean for the new tentative plan
        PlanBean newPlan = (PlanBean)session.getAttribute("NewPlan");
        
        //Get user id
        UserBean user = (UserBean)session.getAttribute("user");
                
        
        //Declare items for the connection.
        String url = "jdbc:mysql://localhost/lauglog";
        String dbUserName = "root";
        String dbPassword = "";
        String driver = "com.mysql.jdbc.Driver";
        Connection con = null;

        try{
            //Instantiate the connection
            Class.forName(driver).newInstance();
            con = DriverManager.getConnection(url, dbUserName, dbPassword);
            
            //get the info to be inserted in the db from
            //the temporary plan bean
            String planName = newPlan.getPlanName();
            int duration = newPlan.getDuration();
            String durationType = newPlan.getDurationType();
            int creator = user.getUserID();
            String searchablePrivacy = newPlan.getSearchablePrivacy();
            String viewablePrivacy = newPlan.getViewablePrivacy();
            String tags = newPlan.getTags();
            
            PreparedStatement plan = con.prepareStatement("INSERT INTO plans (PlanName,Duration,DurationType,Creator,SearchablePrivacy,ViewablePrivacy,Tags) VALUES (?,?,?,?,?,?,?)");
            plan.setString(1, planName);
            plan.setInt(2, duration);
            plan.setString(3, durationType);
            plan.setInt(4, creator);
            plan.setString(5, searchablePrivacy);
            plan.setString(6, viewablePrivacy);
            plan.setString(7, tags);
            plan.executeUpdate();
            
            //Get the just created plan's Id
            PreparedStatement plansIdStatement = con.prepareStatement("SELECT MAX(PlanId) AS 'PlanId' FROM plans WHERE Creator = ?");
            plansIdStatement.setInt(1, creator);
            ResultSet plansIdResult = plansIdStatement.executeQuery();
            plansIdResult.first();
            
            int planID = plansIdResult.getInt("PlanId");
            
            EventBean eventBean;
            
            for (int i=0;i<eventCounter;i++){
                try{
                    //Instantiate the connection
                    Class.forName(driver).newInstance();
                    con = DriverManager.getConnection(url, dbUserName, dbPassword);
                    eventBean = (EventBean)session.getAttribute("event"+i);

                    //Get event values from bean
                    String eventName = eventBean.getEventName();
                    String eventType = eventBean.getEventType();
                    int eventRepeatRate = eventBean.getRepeatNumber();
                    boolean [] eventDays = eventBean.getDaysOfWeek();
                    
                    //have to turn boolean array into varchar for storage in db
                    String daysOfWeek = "";
                    
                    if(eventDays[0] == true){
                        daysOfWeek+="M";
                    }
                    if(eventDays[1] == true){
                        daysOfWeek+="T";
                    }
                    if(eventDays[2] == true){
                        daysOfWeek+="W";
                    }
                    if(eventDays[3] == true){
                        daysOfWeek+="H";
                    }
                    if(eventDays[4] == true){
                        daysOfWeek+="F";
                    }
                    if(eventDays[5] == true){
                        daysOfWeek+="S";
                    }
                    if(eventDays[6] == true){
                        daysOfWeek+="U";
                    }
                    
                    
                    
                    //Add event to table
                    PreparedStatement eventStatement = con.prepareStatement("INSERT INTO events (PlanId, Name, Type, RepeatRate, DayOfWeek) VALUES (?,?,?,?,?)");
                    eventStatement.setInt(1, planID);
                    eventStatement.setString(2, eventName);
                    eventStatement.setString(3, eventType);
                    eventStatement.setInt(4, eventRepeatRate);
                    eventStatement.setString(5, daysOfWeek);
                    eventStatement.executeUpdate();
                    
                    
                }catch(Exception e){
                    e.printStackTrace();
                }finally{
                    try{
                        con.close();
                    }catch(Exception e1){
                        e1.printStackTrace();
                    }
                }
                //get rid of the temporary events beans
                session.removeAttribute("event"+i);
            }
            
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            try{
                con.close();
            }catch(Exception e1){
                e1.printStackTrace();
            }
        }
        
        //get rid of the temporary plan beans
        session.removeAttribute("NewPlan");
        
        //reset event counter
        eventCounter=0;
        
        //update the userPlansBean
        updateUserPlansBean(request);
        
        //send the user back to the list of plans
        response.sendRedirect("plans.jsp");
        
        
    }
    
    private void updatePlan(HttpServletRequest request, HttpServletResponse response) {
        
    }
    
    private void planEdit(int planId) {
        
    }
    
    private void pushPlan(int patientId, int planId){
        
    }

    private void createEvent(HttpServletRequest request, HttpServletResponse response) {
        String [] daysOfWeekValues;
        boolean [] daysOfWeekBools = {false,false,false,false,false,false,false};
        HttpSession session = request.getSession();
        EventBean temp = new EventBean();
        temp.setEventName(request.getParameter("EventName"));
        temp.setEventType(request.getParameter("EventType"));
        daysOfWeekValues = request.getParameterValues("DaysOfWeek");
        for (int i=0; i<daysOfWeekValues.length; i++)
        {
            int day;
            day = Integer.parseInt(daysOfWeekValues[i]);
            daysOfWeekBools[day] = true;
        }
        temp.setDaysOfWeek(daysOfWeekBools);
        temp.setRepeatNumber(Integer.parseInt(request.getParameter("RepeatNumber")));
        session.setAttribute("event" + eventCounter, temp);
        eventCounter++;
    }
    
    private void updateEvent(HttpServletRequest request, HttpServletResponse response) {
        
    }
    
    private void clearEvents(){
        
    }
    private void updateUserPlansBean(HttpServletRequest request){
        
        UserBean user = (UserBean)request.getSession().getAttribute("user");
        int userID = user.getUserID();
        
        //Initiate variables for database queries
        String url = "jdbc:mysql://localhost/lauglog";
        String dbUserName = "root";
        String dbPassword = "";
        String driver = "com.mysql.jdbc.Driver";
        
        Connection con = null;
        try{
            
            //Make the connection
            Class.forName(driver).newInstance();
            con = DriverManager.getConnection(url, dbUserName, dbPassword);
            
            //
            
            PreparedStatement userPlansStatement = con.prepareStatement("SELECT PlanName,PlanId FROM plans WHERE Creator = ?");
            userPlansStatement.setInt(1, userID);
            ResultSet userPlansRs = userPlansStatement.executeQuery();
            
            UserPlansBean userPlansBean = new UserPlansBean();
            Vector<MadePlan> planVector = new Vector();
            while(userPlansRs.next()){
                               
                MadePlan m = new MadePlan();
                m.setPlanID(userPlansRs.getInt("PlanId"));
                m.setPlanName(userPlansRs.getString("PlanName"));
                m.setJoined(false);
                
                planVector.add(m);
                
            }
            
            PreparedStatement userJoinedPlansStatement = con.prepareStatement("SELECT PlanId FROM joined_plans WHERE UserId = ?");
            userJoinedPlansStatement.setInt(1,userID);
            ResultSet userJoinedPlansRs = userJoinedPlansStatement.executeQuery();
            
            while(userJoinedPlansRs.next()){
                int thisPlanId = userJoinedPlansRs.getInt("PlanId");
                
                for(int i = 0; i < planVector.size(); i++){
                    if(planVector.get(i).getPlanID() == thisPlanId){
                        planVector.get(i).setJoined(true);
                    }
                }
            }
            
            
            userPlansBean.setListPlans(planVector);
            //Place the bean into the session
            HttpSession session = request.getSession();
            session.setAttribute("userPlans",userPlansBean);
            
            
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            try{
                con.close();
            }catch(Exception e){
                
            }
        }
    }
}
